package com.asa.ripperview

import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.widget.ImageView
import androidx.constraintlayout.widget.Placeholder
import androidx.core.widget.ImageViewCompat
import androidx.databinding.BindingAdapter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.load.resource.gif.GifDrawable
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target

/**
 * create By：anderson
 * on 2022/2/27
 * desc:
 */



@BindingAdapter(value = ["source","placeHolder","isCircleCrop","roundCorners"],requireAll = false)
fun ImageView.setData(source:Any?,placeholder: Any?,isCircleCrop: Boolean,roundCorners:Float){
    val requestManager = Glide.with(context)
    val requestBuilder = when(source){
        is String-> {
            if (source.endsWith(".gif")){
                requestManager.asGif().load(source).listener(object :RequestListener<GifDrawable>{
                    override fun onLoadFailed(
                        e: GlideException?,
                        model: Any?,
                        target: Target<GifDrawable>?,
                        isFirstResource: Boolean
                    ): Boolean {
                        return false
                    }

                    override fun onResourceReady(
                        resource: GifDrawable?,
                        model: Any?,
                        target: Target<GifDrawable>?,
                        dataSource: DataSource?,
                        isFirstResource: Boolean
                    ): Boolean {
                        if (resource is GifDrawable){
                            resource.setLoopCount(2) // gif只播放一次
                        }
                        return false
                    }
                })
            } else{
                requestManager.load(source)
            }
        }
        is Drawable -> requestManager.load(source)
        is Bitmap -> requestManager.load(source)
        is Int->requestManager.load(source)
        else -> requestManager.load("")
    }

    if (placeholder != null){
        if (placeholder is Drawable){
            requestBuilder.apply(RequestOptions.placeholderOf(placeholder))
        } else if (placeholder is Int){
            requestBuilder.apply(RequestOptions.placeholderOf(placeholder))
        }
    }
    if (isCircleCrop){
        requestBuilder.apply(RequestOptions.bitmapTransform(CircleCrop()))
    }

    if (roundCorners>0f){
        requestBuilder.apply(RequestOptions.bitmapTransform(RoundedCorners(roundCorners.toInt())))
    }
    requestBuilder.into(this)
}
